import { memo, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { RouterProvider } from "react-router-dom";
import { layoutRouter, commonRoutes, dynamicRoutes } from "./router";

import router from "./router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken } from "@/utils/token";

NProgress.configure({ showSpinner: false, easing: "linear", speed: 400, minimum: 0.1 });
let timer = null;
router.beforeEach = function (to) {
  if (!getToken().accessToken && to.pathname !== "/login") {
    return router.browserRouter.navigate("/login");
  }
  NProgress.start();
  timer = setInterval(() => NProgress.inc(), 200);
};

router.afterEach = function () {
  NProgress.done();
  timer && clearInterval(timer);
};

const Router = () => {
  const routerStore = useSelector((state) => state.router.routes);
  const [values, setValues] = useState(null);

  useEffect(() => {
    if (routerStore.length) {
      router.setRoutes(commonRoutes.concat(dynamicRoutes));
      router.addRoutes({ ...layoutRouter, children: JSON.parse(JSON.stringify(routerStore)) });
    }
    setValues(router.browserRouter);
  }, [routerStore]);

  return values && <RouterProvider router={values} />;
};

export default memo(Router);
